package com.javacv4axe.example;

import org.axe.util.LogUtil;
import org.axe.util.StringUtil;
import org.bytedeco.javacpp.opencv_core.Mat;
import org.bytedeco.javacpp.opencv_imgproc;
import org.bytedeco.javacpp.opencv_objdetect.QRCodeDetector;
import org.bytedeco.javacv.Frame;

import com.javacv4axe.core.AsynchronousFrameHandler;
import com.javacv4axe.core.FramePack;


/**
 * 二维码检测Handler
 * @author Administrator
 *
 */
public class QrCodeDetectHandler extends AsynchronousFrameHandler{
	// 二维码检测器
	private QRCodeDetector qrCodeDetector = new QRCodeDetector();
	
	public QrCodeDetectHandler() {
		if(debug()){
			LogUtil.log(name()+"，初始化完成");
		}
	}
	
	@Override
	public final boolean handle(FramePack framePack) {
		try {
			// 摄像头是彩色的图像，要先灰度化
			Mat grayMat = new Mat();
			// 二维码要全画幅检测
			opencv_imgproc.cvtColor((Mat)framePack.getFullFrame().opaque, grayMat, opencv_imgproc.COLOR_BGRA2GRAY);
			// 检测二维码
			String code = qrCodeDetector.detectAndDecode((grayMat).getUMat(0));
			if(debug()){
				LogUtil.log(name()+" qrcode detected:"+code);
			}
			if (StringUtil.isNotEmpty(code)) {
				qrCodeDetected(framePack.getFullFrame(),code);
				return true;
			}
			return false;
		} catch (Exception e) {
			LogUtil.error(e);
			return false;
		}
	}
	
	@Override
	public String name() {
		return "二维码识别Handle Timer";
	}
	
	public void qrCodeDetected(Frame frame,String result) {
		LogUtil.log("发现二维码："+result);
	}

	@Override
	public double timeSec() {
		return 0.5;
	}
	
}
